/**
 * user
 * Email: thedanyang@qq.com
 * Date: 2024-02-06 10:21:08
 * Author: deary
 * Copyright (c) 2021 AYY
 */

import { defineStore } from "pinia";
import { isEmpty } from "@/uni_modules/deary-utils/js_sdk/index.js";
import { getLocalUserInfo, getToken, setToken } from "@/utils/storage.js";

export const useUserStore = defineStore("user", {
  state: () => {
    return {
      isLogin: false,
      token: getToken(),
      oUserInfo: getLocalUserInfo()
    };
  },
  actions: {
    // 初始化服务器公钥
    loadIsLogin() {
      this.isLogin = !isEmpty(this.token);
    },
    // todo 获取用户信息
    loadUserInfo() {
      return this.oUserInfo;
    },
    // todo 手机号登录
    loginByPhone(data) {
      return new Promise((resolve, reject) => {
        console.log(data);
      });
    },
    // todo 获取微信用户信息
    loadWeChatUserInfo(data) {
      return new Promise((resolve, reject) => {
        uni.getUserProfile({
          desc: "帮助您登录并使用小程序",
          lang: "zh_CN",
          success: (res) => {
            console.log(res);
            this.loginByWeChat().then((loginRes) => {
              resolve(loginRes);
            });
          },
          fail: (err) => {
            reject(err);
          }
        });
      });
    },
    // todo 微信登录
    loginByWeChat() {
      return new Promise((resolve, reject) => {
        uni.login({
          success(loginRes) {
            console.log(loginRes.code);
            this.isLogin = true;
            setToken("123");
            resolve();
          },
          fail(err) {
            console.error("uni login fail", err);
            reject();
          }
        });
      });
    },
    removeLoginInfo() {
      return new Promise((resolve) => {
        this.isLogin = false;
        this.token = "";
        this.oUserInfo = {};
        resolve();
      });
    }
  }
});
